package su.myspringbootprojects.springsecuritylearn.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import su.myspringbootprojects.springsecuritylearn.service.DatabaseUserDetailsService;

/**
 * Класс SecurityConfig
 * <p/>
 * Конфигурация прав доступа для различных пользователей и групп
 * <p/>
 *
 * @author petr.mikhailin
 * created 04.07.2024 8:27
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    private final DatabaseUserDetailsService databaseUserDetailsService;

    @Autowired
    public SecurityConfig(DatabaseUserDetailsService databaseUserDetailsService) {
        this.databaseUserDetailsService = databaseUserDetailsService;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity securityConfig) throws Exception {
        return securityConfig
                .authorizeHttpRequests(auth-> auth
                    .requestMatchers("/api/hello").permitAll()
                    .requestMatchers("/api/admin").hasRole("ADMIN")
                .anyRequest().authenticated())
                .formLogin(Customizer.withDefaults())
                .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        //set the user details object
        authenticationProvider.setUserDetailsService(databaseUserDetailsService);
        //set the password encoder
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
}
